import logging

from flask import Blueprint, request
from flask import jsonify

from airflow.patsnap.service import auth_service
from airflow.exceptions import AirflowException
from airflow.www.api import provide_user

log = logging.getLogger(__name__)

api_speech_auth = Blueprint('api_speech_auth', __name__)


# user route
@api_speech_auth.route('/auth/is_path_auth/', methods=['GET'])
@provide_user
def is_path_auth(oa_user_name):
    try:
        path = request.values.get("path", type=str, default=None)
        if path is None:
            log.error("is_path_auth params error path={%s}", path)
            return jsonify(code=500, message="is_path_auth params has None,", data=None)

        have_path = auth_service.is_path_auth(path, oa_user_name)
        if have_path:
            return jsonify(code=200, message='ok', data=have_path)
        else:
            return jsonify(code=403, message='no Permission', data=have_path)
    except AirflowException as e:
        log.error("is_path_auth error =%s", e, )
        return jsonify(code=500, message=str(e), data=None)


@api_speech_auth.route('/auth/apply_token/', methods=['GET'])
def auth_apply_tokens():
    try:
        oa_user_name = request.args.get("username", type=str, default=None)
        if oa_user_name is None:
            log.error("apply_token params error username={%s}", oa_user_name)
            return jsonify(code=400, message="applyToken params has None,", data=None)

        result = auth_service.apply_token(oa_user_name)
        return jsonify(code=0, message='ok', data=result)
    except AirflowException as e:
        log.error("apply_token error =%s", e, )
        return jsonify(code=500, message=str(e), data=None)


@api_speech_auth.route('/auth/login/', methods=['POST'])
def apply_token():
    try:
        username = request.values.get("username", type=str, default=None)
        password = request.values.get("password", type=str, default=None)
        if username is None or password is None:
            log.error("login params error username={%s},password={%s}", username, password)
            return jsonify(code=400, message="login params has None,", data=None)

        result = auth_service.login(username, password)
        if result:
            return jsonify(code=0, message='ok', data=result)
        else:
            return jsonify(code=401, message='ok', data=result)
    except AirflowException as e:
        log.error("login error =%s", e, )
        return jsonify(code=500, message=str(e), data=None)

